<template>
  <div role="alert" :class="getAlertClass()"
       class="message fixed z-50 transition-all duration-300"
       :style="{
        opacity: isVisible? '1' : '0',
        transform: isVisible? 'translate(-50%, 0)' : 'translate(-50%, -20px)',
        left: '50%',
        top: props.top,
        transformOrigin: 'top'
      }"
  >
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="h-6 w-6 shrink-0 stroke-current">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="getIconPath()"/>
    </svg>
    <span>{{ message }}</span>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineProps, defineEmits } from 'vue';

const props = defineProps({
  message: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    default: 'info',
    validator: (value) => ['success', 'warning', 'error', 'info'].includes(value),
  },
  duration: {
    type: Number,
    default: 3000,
  },
  top: {
    type: String,
    default: '20px',
  },
});

const emits = defineEmits(['close']);

const isVisible = ref(true);

// 根据类型获取对应的图标路径
const getIconPath = () => {
  switch (props.type) {
    case'success':
      return 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z';
    case 'warning':
      return 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z';
    case 'error':
      return 'M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z';
    case 'info':
      return 'M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z';
    default:
      return 'M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z';
  }
};

// 根据类型获取对应的 DaisyUI 类
const getAlertClass = () => {
  switch (props.type) {
    case'success':
      return 'alert alert-success';
    case 'warning':
      return 'alert alert-warning';
    case 'error':
      return 'alert alert-error';
    case 'info':
      return 'alert alert-info';
    default:
      return 'alert alert-info';
  }
};

const closeMessage = () => {
  isVisible.value = false;
  emits('close');
};

onMounted(() => {
  if (props.duration > 0) {
    setTimeout(() => {
      closeMessage();
    }, props.duration);
  }
});

onUnmounted(() => {
  // 清理定时器（这里可以补充具体清理逻辑，当前代码逻辑里没有实际创建定时器，可忽略）
});
</script>

<style scoped>
.message {
  transform: translateY(-20px);
  opacity: 0;
  transition: opacity 0.3s ease, transform 0.3s ease;
}
</style>